package com.riddle.admin.controller;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.riddle.model.User;
import com.riddle.service.UserService;
import com.riddle.util.Constant;
import com.riddle.util.JsonUtil;
import com.riddle.vmodel.VMsg;

@Controller
@RequestMapping("/admin/home")
public class AdminController {

	@Resource
	private UserService userService;
	
	@RequestMapping()
	public ModelAndView index() {
		return new ModelAndView("admin/index");
	}
	
	@RequestMapping("/login")
	public ModelAndView login() {
		return new ModelAndView("admin/login");
	}
	
	@RequestMapping("/loginaction")
	public ModelAndView login(User user) {
		Subject subject = SecurityUtils.getSubject();
		if(!subject.isAuthenticated()) {
			
			try {
				String password = new Md5Hash(user.getPassword()).toString();
				UsernamePasswordToken token = new UsernamePasswordToken(user.getName(), password);
				token.setRememberMe(false);
				subject.login(token);
				User currentUser = userService.getUser(user.getName());
				subject.getSession().setAttribute(Constant.CurrentUser, currentUser);
				return new ModelAndView("redirect:/admin/home");
			} catch(UnknownAccountException ex) {
				
			} catch (IncorrectCredentialsException ex) {
				
			} catch (Exception ex) {
				
			}
		}
		return new ModelAndView("redirect:/admin/home/login");
	}
	
	@RequestMapping(value="/logout", produces="application/json;charset=utf-8")
	@ResponseBody
	public String logout() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		VMsg msg = new VMsg();
		msg.setMessage("success");
		return JsonUtil.toJson(msg);
	}
}
